package com.chezhujie.www.controller;

import com.chezhujie.www.core.StaticMap;
import com.chezhujie.www.domain.*;
import com.chezhujie.www.domain.vo.Coupons;
import com.chezhujie.www.enums.AwardType;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.enums.OrderType;
import com.chezhujie.www.enums.RefundStatus;
import com.chezhujie.www.service.*;
import com.xy.core.page.Pagination;
import com.xy.user.base.controller.BaseController;
import com.xy.core.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by 汤伟杰 on 2017/6/1.
 */
@Controller
@RequestMapping("/api1")
public class ApitwjController extends BaseController {
    @Autowired
    private Czjcommodity3Service czjcommodity3Service;
    @Autowired
    private ApitwjService apitwjService;
    @Autowired
    private CzjreplyService czjreplyService;
    @Autowired
    private CzjcommentsService czjcommentsService;
    @Autowired
    private CzjcommodityService czjcommodityService;
    @Autowired
    private CzjorderdetailService czjorderdetailService;
    @Autowired
    private CzjorderService czjorderService;
    @Autowired
    private CzjorderdistributionService czjorderdistributionService;
    @Autowired
    private CzjdeliveryaddService czjdeliveryaddService;
    @Autowired
    private CzjactivityService czjactivityService;
    @Autowired
    private CzjfestivalactService czjfestivalactService;
    @Autowired
    private CzjdataresourceService czjdataresourceService;
    @Autowired
    private CzjactdetailService czjactdetailService;
    @Autowired
    private CzjtordermemberService czjtordermemberService;
    @Autowired
    private CzjtordermemberdetailService czjtordermemberdetailService;
    @Autowired
    private CzjmemberService czjmemberService;
    @Autowired
    private CzjshopcarService czjshopcarService;
    @Autowired
    private CzjcommodityimageService czjcommodityimageService;
    @Autowired
    private CzjspecificationService czjspecificationService;
    @Autowired
    private CzjaftersalesService czjaftersalesService;
    @Autowired
    private CzjrefundService czjrefundService;
    @Autowired
    private CzjrefundimageService czjrefundimageService;
    @Autowired
    private CzjrefundvideoService czjrefundvideoService;
    @Autowired
    private CzjawardstockService czjawardstockService;
    @Autowired
    private CzjpayorderService czjpayorderService;
    @Autowired
    private CzjfestpicService czjfestpicService;
    @Autowired
    private Czjtop3Service czjtop3Service;
    @Autowired
    private CzjawarduseService czjawarduseService;
    @Autowired
    private WeixininfoService weixininfoService;
    @Autowired
    private CzjawardonService czjawardonService;
    @Autowired
    private CzjusecouponService czjusecouponService;



    /**
     * 首页3个商品
     *
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/commoditylist3.jn")
    public void list3(HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) throws Exception {
        try {
            List<Map<String, Object>> listmap = czjcommodity3Service.getList3(new HashMap<String, Object>());
            for (int i = 0; i < listmap.size(); i++) {
                if(listmap.get(i).get("picPath")!=null) {
                    if (StringUtils.isNotBlank(String.valueOf(listmap.get(i).get("picPath")))) {
                        listmap.get(i).put("defaultImage", String.valueOf(listmap.get(i).get("picPath")));
                    }
                }
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", listmap.size());
            map.put("list", listmap);
            jsonResult(1, "0", "", map, resp);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage() + " #error:" + e);
            jsonResult(0, "99", "获取失败！" + e, "", resp);
        }

    }

    /**
     * 商品列表
     *
     * @param pageNo
     * @param pageSize
     * @param czjcommodity
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/commoditylist.jn")
    public void commoditylist(Integer pageNo, Integer pageSize, Czjcommodity czjcommodity, HttpServletRequest req, HttpServletResponse resp,
                              ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            czjcommodity.setSoldOut(0);
            Map<String, Object> params = ConvertObj.toMap(czjcommodity);
            Pagination pagination = czjcommodityService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1, "0", "", pagination, resp);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage() + " #error:" + e);
            jsonResult(0, "99", "获取失败！" + e, "", resp);
        }

    }

    /**
     * 评论
     * @param files     文件集合
     * @param content     评论内容
     * @param objectId  对象id
     * @param objectType  类型 ：0是活动评论 1是商品评论
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/commentsAdd.jn")
    public void commentsAdd(@RequestParam(value = "files",required = false) MultipartFile[] files,
                            Integer joinlpk,//是否参加乐拍客
                            String content,@RequestParam(required = true) String objectId,@RequestParam(required = true)int objectType,
                            @RequestParam(required = true) int userinfoId,
                            HttpServletRequest req, HttpServletResponse resp,
                            ModelMap model) throws Exception {
        if(objectType==0){
            //活动评论
        	Map<String, Object> param=new HashMap<String, Object>();
        	param.put("festivalActId", objectId);
           Czjfestivalact czjfestivalact= czjfestivalactService.getCzjfestivalact(param);
           if(null==czjfestivalact){
        	   jsonResult(0, "134", "活动不存在", "", resp);
        	   return ;
           }
        }else if(objectType==1){
            //商品评论
            Czjcommodity czjcommodity = czjcommodityService.queryById(objectId);
            if(null==czjcommodity) {
                jsonResult(0,"010","评论商品不存在","",resp);
                return;
            }
        }else{
            log.info("log info:传入评论类型不正确！");
            jsonResult(0,"012","传入评论类型不正确！","",resp);
            return;
        }


        List<MultipartFile> vidfiles = getImageYN(files,0);//得到视频集合
        List<MultipartFile> picfiles = getImageYN(files,1);//得到图片集合
        try {
            apitwjService.saveCommentsBy(joinlpk,vidfiles,picfiles,objectId,content,objectType,userinfoId,req);//类型 ：0是活动评论 1是商品评论
            jsonResult(1,"0","新增评论成功","",resp);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("log error:"+e);
            jsonResult(0,"099","新增评论失败！"+e.getMessage(),"",resp);
        }
    }

    /**
     * 新增回复
     * @param content
     * @throws Exception
     */
    @RequestMapping("/replyAdd.jn")
    public void replyAdd(@RequestParam(required = true) String content, String commentsId, String parentReplyId,
                            @RequestParam(required = true) int userinfoId,
                            HttpServletRequest req, HttpServletResponse resp,
                            ModelMap model) throws Exception {
        try {
            if(StringUtils.isNotBlank(parentReplyId)){
                Czjreply czjreplyP =czjreplyService.queryById(parentReplyId);
                if(czjreplyP==null){
                    jsonResult(0,"99","回复上一级回复不存在！","",resp);
                    return;
                }
                Czjreply czjreply = new Czjreply();
                czjreply.setReplyId(UUIDUtils.getUUID());
                czjreply.setContent(content);
                czjreply.setCommentsId(czjreplyP.getCommentsId());
                czjreply.setApproveStatus(0);
                czjreply.setCreatetime(new Date());
                czjreply.setUserinfoId(userinfoId);
                czjreply.setParentReplyId(czjreplyP.getReplyId());
                czjreplyService.checkEntity(czjreply);
                czjreplyService.insert(czjreply);
            }else{
                if(StringUtils.isBlank(commentsId)){
                    jsonResult(0,"14","回复的评论ID不为空","",resp);
                    return;
                }
                Czjcomments czjcomments = czjcommentsService.queryById(commentsId);
                if(czjcomments==null){
                    jsonResult(0,"15","回复的评论不存在","",resp);
                    return;
                }
                Czjreply czjreply = new Czjreply();
                czjreply.setReplyId(UUIDUtils.getUUID());
                czjreply.setContent(content);
                czjreply.setCommentsId(commentsId);
                czjreply.setApproveStatus(0);
                czjreply.setCreatetime(new Date());
                czjreply.setUserinfoId(userinfoId);
                czjreply.setParentReplyId(null);
                czjreplyService.checkEntity(czjreply);
                czjreplyService.insert(czjreply);
            }
            jsonResult(1,"","回复成功","",resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","程序出错！"+e,"",resp);
        }


    }



    /**
     * 生成订单
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/generateOrder.jn")
    public void generateOrder(@RequestParam(required = true) Integer userinfoId,//用户id
                              @RequestParam(required = true) Integer count,//支付物品数量
                              @RequestParam(required = true) String objectId,//支付物品id
                              @RequestParam(required = false) String distributionId,//选择配送地址的id
                              @RequestParam(required = false) String remarks,//配送备注
                              String couponsId,//优惠id
                              HttpServletRequest req, HttpServletResponse resp,
                              ModelMap model) throws Exception {
        try{
            if(count==null||count==0){
                count=1;
            }

            String orderCode = null;
            String title = "";
            BigDecimal salePrice = null;
            Integer orderType =null;
            String businessId = "";
            Integer objectType = Integer.parseInt(objectId.substring(0, 1));
            Integer status = 0;
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("isuse",0);
            map.put("objectId", objectId);

            map.put("objectType",objectType);


            if(objectType==OrderType.ACTIVITY.getIndex()){//生成活动订单
                orderCode = OrderNumUtils.getOrderNo(OrderType.ACTIVITY.getIndex());
                Czjfestivalact czjfestivalact = czjfestivalactService.queryById(objectId);
                if(czjfestivalact==null){
                    jsonResult(0,"70","活动不存在","",resp);
                    return;
                }
            /*    if(!(czjfestivalact.getBeginTime().getTime()<System.currentTimeMillis())){
                    jsonResult(0,"69","活动未开始","",resp);
                    return;
                }*/
                if(!(czjfestivalact.getEndTime().getTime()> System.currentTimeMillis())){
                    jsonResult(0,"71","活动已结束","",resp);
                    return;
                }
                salePrice = czjfestivalact.getFestAmount();
                map.put("salePrice",salePrice);
                Czjactivity czjactivity = new Czjactivity();
                Czjactdetail czjactdetail = new Czjactdetail();
                //订单
                czjactivity.setFree(1);
                czjactivity.setDel(1);
                czjactivity.setHide(1);
                czjactivity.setUserinfoId(userinfoId);
                czjactivity.setActivityId(UUIDUtils.getUUID());
                czjactivity.setCreatetime(new Date());
                czjactivity.setBusinessId(businessId);
                czjactivity.setActivityNum(orderCode);

                czjactivity.setTotalAmount(coupons(salePrice.multiply(new BigDecimal(count)),couponsId,map));
                czjactivity.setStatus(OrderStatus.RUNNING.getIndex());
                czjactivity.setBusinessId("1");
                if(Integer.parseInt(String.valueOf(map.get("isuse")))==1) {
                    czjactivity.setCouponsId(couponsId);
                }

                if(czjactivity.getTotalAmount().compareTo(BigDecimal.ZERO)==0){
                    status=1;
                }

                //订单详情
                czjactdetail.setActivityNum(orderCode);
                czjactdetail.setActDetaiId(UUIDUtils.getUUID());
                czjactdetail.setFestivalActId(czjfestivalact.getFestivalActId());
                czjactdetail.setBuyingPrice(salePrice.multiply(new BigDecimal(count)));
                czjactdetail.setCreatetime(new Date());
                czjactdetail.setNun(count);
                czjactdetail.setTitle(czjfestivalact.getFestName());
                czjactdetail.setFestAmount(salePrice);
                czjactivityService.insertActivity(czjactivity);
                czjactdetailService.insertCzjactdetail(czjactdetail);
                //0元支付情况，支付金额为0情况，就直接支付完成了
                if(status==1){
                    czjactivityService.updateOrderStatus(orderCode, OrderStatus.UNUSE.getIndex());
                    if(StringUtils.isNotBlank(couponsId)){
                        //使用后更改优惠券状态为已使用
                        Czjawarduse czjawarduse32 = new Czjawarduse();
                        czjawarduse32.setAwarduseId(couponsId);
                        Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
                        czjawarduse.setStatus(OrderStatus.USE.getIndex());
                        czjawarduseService.updateCzjawarduse(czjawarduse);
                        czjusecouponService.businessSave(couponsId, orderCode);//cp一份给订单详情查看
                    }
                }

                map.put("price", czjactivity.getTotalAmount());
            }else if(objectType==OrderType.COMMODITY.getIndex()){//生成商品订单
                orderCode = OrderNumUtils.getOrderNo(OrderType.COMMODITY.getIndex());
                Czjcommodity czjcommodity = czjcommodityService.queryById(objectId);
                if(czjcommodity==null){
                    jsonResult(0,"41","商品不存在，或者商品已下架","",resp);
                    return;
                }
                title = czjcommodity.getCommodityName();
                businessId = czjcommodity.getBusinessId();
                orderType = OrderType.COMMODITY.getIndex();
                salePrice = czjcommodity.getPresentPrice();
                map.put("salePrice",salePrice);
                Czjorder czjorder = new Czjorder();
                Czjorderdetail czjorderdetail = new Czjorderdetail();
                Czjorderdistribution czjorderdistribution = new Czjorderdistribution();
                //订单
                czjorder.setUserinfoId(userinfoId);
                czjorder.setId(UUIDUtils.getUUID());
                czjorder.setCreateTime(new Date());
                czjorder.setOrderType(orderType);
                czjorder.setBusinessId(businessId);
                czjorder.setOrderCode(orderCode);
                czjorder.setPaymentType(0);
                czjorder.setTotalAmount(coupons(salePrice.multiply(new BigDecimal(count)),couponsId, map));
                czjorder.setStatus(OrderStatus.RUNNING.getIndex());
                if(Integer.parseInt(String.valueOf(map.get("isuse")))==1) {
                    czjorder.setCouponsId(couponsId);
                }


                if(czjorder.getTotalAmount().compareTo(BigDecimal.ZERO)==0){
                    status=1;


                }

                //订单详情
                czjorderdetail.setOrderCode(orderCode);
                czjorderdetail.setId(UUIDUtils.getUUID());
                czjorderdetail.setCreateTime(new Date());
                czjorderdetail.setAmount(count);
                czjorderdetail.setCommodityId(objectId);
                czjorderdetail.setSalePrice(salePrice);
                czjorderdetail.setTitle(title);

                czjorderdetailService.checkEntity(czjorderdetail);
                czjorderService.checkEntity(czjorder);
                if(StringUtils.isNotBlank(distributionId)){
                    //订单配送地址
                    Czjdeliveryadd deliveryadd = czjdeliveryaddService.queryById(distributionId);
                    czjorderdistribution.setId(UUIDUtils.getUUID());
                    czjorderdistribution.setAddress((deliveryadd.getRegion()==null?"":deliveryadd.getRegion())+" "+(deliveryadd.getAddress()==null?"":deliveryadd.getAddress()));
                    czjorderdistribution.setCreateTime(new Date());
                    czjorderdistribution.setEmail(null);
                    czjorderdistribution.setPhoneNo(deliveryadd.getPhone());
                    czjorderdistribution.setOrderCode(orderCode);
                    czjorderdistribution.setPostalCode(null);
                    czjorderdistribution.setRecipients(deliveryadd.getName());
                    czjorderdistribution.setMessage(remarks);
                    czjorderdistributionService.checkEntity(czjorderdistribution);
                    czjorderdistributionService.insert(czjorderdistribution);

                }else{
                    jsonResult(0,"40","收货地址必须要选","",resp);
                    return;
                }
                czjorderdetailService.insert(czjorderdetail);
                czjorderService.insert(czjorder);
                //0元支付情况，支付金额为0情况，订单自动完成
                if(status==1){

                    //增加已售量
                    Czjcommodity comodity = czjcommodityService.queryById(czjorderdetail.getCommodityId());
                    if(comodity.getSoldOut()==null){
                        comodity.setSoldOut(0);
                    }
                    if(czjorderdetail.getAmount()==null){
                        czjorderdetail.setAmount(0);
                    }
                    comodity.setSoldOut(comodity.getSoldOut()+czjorderdetail.getAmount());
                 /*   comodity.setInventory(comodity.getInventory()-czjorderdetail.getAmount());
                    if(comodity.getInventory()<0){
                        jsonResult(0,"65","该商品已售完","",resp);
                        return;
                    }*/
                    czjcommodityService.update(comodity);
                    Czjorderdistribution orderdistribution = czjorderdistributionService.getByOrderno(orderCode);
                    if(StringUtils.isNotBlank(couponsId)){
                        //使用后更改优惠券状态为已使用
                        Czjawarduse czjawarduse32 = new Czjawarduse();
                        czjawarduse32.setAwarduseId(couponsId);
                        Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
                        czjawarduse.setStatus(OrderStatus.USE.getIndex());
                        czjawarduseService.updateCzjawarduse(czjawarduse);
                        czjusecouponService.businessSave(couponsId, orderCode);//cp一份给订单详情查看
                    }
                    if(orderdistribution==null){
                        czjorderService.updateOrderStatus(orderCode,OrderStatus.FIN.getIndex());
                    }else{
                        czjorderService.updateOrderStatus(orderCode,OrderStatus.TOSENDGOODS.getIndex());
                    }
                }
                map.put("price", czjorder.getTotalAmount());
            }else{
                jsonResult(0,"45","不是商品或者活动!","",resp);
                return;
            }
          /*  if(Integer.parseInt(String.valueOf(map.get("isuse")))==1){
                //使用后更改优惠券状态为已使用
                Czjawarduse czjawarduse32 = new Czjawarduse();
                czjawarduse32.setAwarduseId(couponsId);
                Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
                czjawarduse.setStatus(5);
                czjawarduseService.updateCzjawarduse(czjawarduse);
            }
*/



            map.put("orderno", orderCode);
            map.put("status", status);

            jsonResult(1,"","生成订单",map,resp);
            return;
        }catch (Exception e){
            e.printStackTrace();
            log.error("#error:",e);
            jsonResult(0,"99","生成订单失败","",resp);
            return;
        }

    }
    /** 返回优惠之后的价格 */
    private BigDecimal coupons(BigDecimal decimal, String couponsId, Map<String, Object> map) {

        if(StringUtils.isBlank(couponsId)){
            return decimal;
        }
        Coupons coupons= czjawardstockService.queryMapById(couponsId);
        //判断是否过期
        // 1活动优惠劵,2商品优惠券,3实物商品,4红包,5活动优惠名额,6谢谢参与
        if(coupons==null||coupons.getValidDate()==null||coupons.getPrice()==null||coupons.getCouponsId()==null
               ){
            return decimal;
        }

        if(coupons.getValidDate().getTime()<System.currentTimeMillis()){
            System.out.println("该优惠券/优惠名额("+couponsId+")已过期");
            return decimal;
        }
        if(coupons.getStatus()==4){//在使用状态才可以使用优惠券或者优惠名额
            BigDecimal bigDecimal = null;
            if(coupons.getAwardType()==2) {//优惠券使用
                bigDecimal = coupons.getPrice();
//                String objectId = String.valueOf(map.get("objectId"));
//                Integer objectType = Integer.valueOf(String.valueOf(map.get("objectType")));

//                if(objectType==OrderType.ACTIVITY.getIndex()) {
//                    Czjactivity czjactivity = czjactivityService.queryById(objectId);
//                }else if( objectType==OrderType.COMMODITY.getIndex()) {
//                    Czjcommodity czjcomment2 = czjcommodityService.queryById(objectId);
//                }


            }else  if(coupons.getAwardType()==5) {//优惠名额使用
                //检查是否是一样的活动
               if(String.valueOf(map.get("objectId")).equals(coupons.getActId())){
                   bigDecimal = new BigDecimal(String.valueOf(map.get("salePrice")));
               }else{
                   //不是一样的活动
                   System.out.println("该优惠名额使用场景（活动）不一致");
                   return decimal;
               }


            }else {
                System.out.println("该优惠不是优惠券或者优惠名额");
                return decimal;
            }
            BigDecimal bg = decimal.subtract(bigDecimal);

            if (bg.compareTo(BigDecimal.ZERO) != 1) {
                bg = new BigDecimal("0");
            }
            map.put("isuse", 1);

            return bg;
        }else{    System.out.println("该优惠券/优惠名额不是未使用状态");
            return decimal;
        }





    }

    /**.
     * 通过经纬度获取地址详细
     * @param location
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/getAddressDetail.jn")
    public void getAddressDetail(@RequestParam(required = true) String location,
                              HttpServletRequest req, HttpServletResponse resp,
                              ModelMap model) throws Exception {
        try {
            Map<String,Object> map = CommonHttp.send("http://apis.map.qq.com/ws/geocoder/v1/?location="+location+"&key="+ StaticMap.MapKey, "get", null);
            if("0".equals(String.valueOf(map.get("status")))){
                Object map1 = ((Map) map.get("result")).get("ad_info");
                jsonResult(1,"","",map1,resp);
            }else{
                jsonResult(0,"",String.valueOf(map.get("message")),"",resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","请求通过经纬度获取地址详细失败！后台异常！","",resp);
        }

    }
    @RequestMapping("/sendHttp.jn")
    public void sendHttp(@RequestParam(required = true) String t_url, HttpServletRequest req, HttpServletResponse resp,
                                 ModelMap model) throws Exception {
        Enumeration<String> enums = req.getParameterNames();
        Map<String, String> map = new HashMap<String, String>();
        String name = "";
        while (enums.hasMoreElements()){
            name = enums.nextElement();
            map.put(name, String.valueOf(req.getParameter(name)));
        }
        map.remove("t_url");
        try {
            Map<String,Object> map2 = CommonHttp.send(t_url, "get", map);
            jsonResult(1,"","",map2,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","请求通过经纬度获取地址详细失败！","",resp);
        }


    }

    /**
     * 加入购物车
     * @param comodityId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
     @RequestMapping("/addShopcar.jn")
    public void addShopcar(String comodityId,Integer userId, String content,Integer count,
                           HttpServletRequest req, HttpServletResponse resp,
                                 ModelMap model) throws Exception {
         try {
             if(StringUtils.isNotBlank(comodityId)&&!"undefined".equals(comodityId)
                     &&userId!=null&&count!=null){
                 Czjshopcar czjshopcar = new Czjshopcar();
                 czjshopcar.setCommodityId(comodityId);
                 czjshopcar.setUserId(userId);
                 List<Map<String, Object>> list = czjshopcarService.getListBy(ConvertObj.toMap(czjshopcar));
                 if(list==null||list.size()==0){
                     Czjcommodity commodity = czjcommodityService.queryById(comodityId);
                     if(commodity!=null){
                         czjshopcar.setBusinessId(commodity.getBusinessId());
                         czjshopcar.setContent(content);
                         czjshopcar.setCreatetime(new Date());
                         czjshopcar.setCount(count==null?0:count);
                         czjshopcar.setShopcarId(UUIDUtils.getUUID());
                         czjshopcarService.insert(czjshopcar);
                         jsonResult(1,"","加入购物车成功","",resp);
                         return;
                     }else{
                         jsonResult(0,"040",comodityId+" 商品不存在！","",resp);
                         return;
                     }

                 }else{
                     jsonResult(1,"","加入购物车成功,购物车已存在","",resp);
                     return;
                 }
             }else{
                 jsonResult(0,"043","comodityId、userId、count不能为空","",resp);
                 return;
             }
         } catch (Exception e) {
             e.printStackTrace();
             log.error("#error",e);
             jsonResult(0,"041","加入购物车异常","",resp);
             return;
         }


     }

    /**
     * 清空购物车上所有商品
     * @param userId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/clearAllShopcar.jn")
    public void clearAllShopcar(Integer userId,
                           HttpServletRequest req, HttpServletResponse resp,
                           ModelMap model) throws Exception {
        try {
            if (userId!=null) {
                Czjshopcar czjshopcar = new Czjshopcar();
                czjshopcar.setUserId(userId);
                List<Map<String, Object>> list = czjshopcarService.getListBy(ConvertObj.toMap(czjshopcar));
                List<String> listIds = new ArrayList<String>();

                if(list!=null&&list.size()>0){
                    for (Map<String, Object> map : list) {
                        listIds.add(String.valueOf(map.get("shopcarId")));
                    }
                }
                if(listIds.size()>0){
                    czjshopcarService.deleteByIds(listIds);
                }
                jsonResult(1,"","清空所有购物车","",resp);
                return;
            } else {
                jsonResult(0,"044","清空所有购物车失败，userId不能为空","",resp);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("#error",e);
            jsonResult(0,"045","清空所有购物车异常","",resp);
            return;
        }


    }

    /**
     * 清空特定商品的购物车
     * @param shopcarId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/clearShopcar.jn")
    public void clearShopcar(String shopcarId,
                           HttpServletRequest req, HttpServletResponse resp,
                           ModelMap model) throws Exception {
        try {
            if(StringUtils.isNotBlank(shopcarId)&&!"undefined".equals(shopcarId)){
                czjshopcarService.deleteById(shopcarId);
                jsonResult(1,"","移除购物车商品成功","",resp);
                return;
            } else {
                jsonResult(0,"046","移除购物车商品失败，comodityId、userId不能为空","",resp);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("#error",e);
            jsonResult(0,"047","移除购物车商品异常","",resp);
            return;
        }


    }

    /**
     * 修改购物车物品数量
     * @param shopcarId
     * @param count
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/updateShopcarCount.jn")
    public void updateShopcarCount(String shopcarId,Integer count,
                             HttpServletRequest req, HttpServletResponse resp,
                             ModelMap model) throws Exception {
        if(StringUtils.isNotBlank(shopcarId)&&!"undefined".equals(shopcarId)&&count!=null){
            Czjshopcar czjshopcar = czjshopcarService.queryById(shopcarId);
            czjshopcar.setCount(count);
            czjshopcarService.update(czjshopcar);
            jsonResult(1,"","修改购物车商品数量成功","",resp);
            return;
        }else{
            jsonResult(0,"048","shopcarId、count不能为空","",resp);
            return;
        }


    }

    /**
     * 购物车列表
     * @param userId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/shopcarList.jn")
    public void shopcarList(Integer userId,
                                   HttpServletRequest req, HttpServletResponse resp,
                                   ModelMap model) throws Exception {
        if(userId!=null){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", userId);
            List<Map<String, Object>> list = czjshopcarService.getApiList(map);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", list);
            jsonResult(1,"","获取购物车列表成功",data,resp);
            return;
        }else{
            jsonResult(0,"049","userId不能为空","",resp);
            return;
        }


    }

    /**
     * 得到优惠券、得到活动名额
     * @param objectId  活动id或者商品id
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/getCoupons.jn")
    public void getCoupons(@RequestParam(required = true)String objectId,@RequestParam(required = true) String userinfoId,
                                 HttpServletRequest req, HttpServletResponse resp,
                                 ModelMap model) throws Exception {

        Integer type=null;
        if(StringUtils.isBlank(userinfoId)){
            userinfoId = "99999999999";
        }
        if(StringUtils.isBlank(objectId)){
            objectId = "99#999999999";
        }
        try {
            type = Integer.parseInt(objectId.substring(0,1));
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","活动id不符合要求，不是正确的活动id","",resp);
            return;
        }

        Map<String, Object> data = new HashMap<String, Object>();
        if(type== OrderType.ACTIVITY.getIndex()){
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userinfoId", userinfoId);
            param.put("activityId", objectId);
            List<Coupons> couponsList= czjawardstockService.queryCouponsBy(param);
            //判断是否过期
            Coupons coupons;
            for (int i = couponsList.size() - 1; i >= 0; i--) {
                coupons = couponsList.get(i);
                if(coupons==null||coupons.getValidDate()==null||coupons.getCouponsId()==null
                        ||coupons.getValidDate().getTime()<System.currentTimeMillis()){//||coupons.getPrice()==null
                    couponsList.remove(i);
                    continue;
                }
                if(coupons.getAwardType()== AwardType.ACTIVITYCOUPONS.getIndex()&&coupons.getPrice()!=null) {
                    //只允许优惠券，而且金额不能为空
                }else if(coupons.getAwardType()==AwardType.PLACES.getIndex()){
                    //只允许优惠名额
                }else{
                    couponsList.remove(i);
                    continue;
                }
            }
            data.put("list",couponsList);

        }else if(type== OrderType.COMMODITY.getIndex()){
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userinfoId", userinfoId);
            param.put("commodityId", objectId);
            List<Coupons> couponsList= czjawardstockService.queryCouponsBy(param);
            //判断是否过期
            Coupons coupons;
            for (int i = couponsList.size() - 1; i >= 0; i--) {
                coupons = couponsList.get(i);
                if(coupons==null||coupons.getValidDate()==null||coupons.getPrice()==null||coupons.getCouponsId()==null
                        ||coupons.getValidDate().getTime()<System.currentTimeMillis()){
                    couponsList.remove(i);
                    continue;
                }
                if(coupons.getAwardType()== AwardType.COMMODITYCOUPONS.getIndex()&&coupons.getStatus()==4){
                    //只允许优惠券
                }else{
                    couponsList.remove(i);
                    continue;
                }
            }
            data.put("list",couponsList);

        }


        jsonResult(1,"","",data,resp);



    }



    /**
     * 获取商品详情
     * @param commodityId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/getCommodityDetail.jn")
    public void getCommodityDetail(@RequestParam(required = true) String commodityId,
                              HttpServletRequest req, HttpServletResponse resp,
                              ModelMap model) throws Exception {

        try{
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("commodityId", commodityId);
            param.put("orderby","t.orderByno");
            param.put("order","asc");
            List<Map<String, Object>> listaftersales = czjaftersalesService.getApiList(param);
            List<Map<String, Object>> lisstspecification = czjspecificationService.getApiList(param);
            Map<String, Object> param2 = new HashMap<String, Object>();
            param2.put("commodityId", commodityId);
            param2.put("picType", 3);
            List<Map<String, Object>> listimage = czjcommodityimageService.getApiList(param2);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("listaftersales",listaftersales);
            data.put("lisstspecification",lisstspecification);
            data.put("listimage",listimage);
            jsonResult(1,"","",data,resp);
        }catch (Exception e){
            e.printStackTrace();
            log.error("#error:",e);
            jsonResult(0,"99","获取售后服务失败","",resp);
        }

    }

    /**
     * 得到商品首页内容
     * @param commodityId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/getCommodityHome.jn")
    public void getCommodityHome(@RequestParam(required = true) String commodityId,
                              HttpServletRequest req, HttpServletResponse resp,
                                   ModelMap model) throws Exception {
        try{
            //商品头像、商品简介、现价、原价、商品名字、商品图片总数
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("commodityId", commodityId);
            Map<String,Object> data = czjcommodityService.queryDetail(map);

            checkCommodity(data);

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("commodityId", commodityId);
            param.put("picType", 0);
            List<Map<String, Object>> map2 = czjcommodityimageService.getApiList(param);
            data.put("imageList",map2);
            //id/imagePath/content/commodityName/originalPrice/presentPrice/soldCount/picCount/commentsCount

            jsonResult(1,"","获取商品详情成功",data,resp);
        }catch (Exception e){
            e.printStackTrace();
            log.error("#error:",e);
            jsonResult(0,"99","获取商品详情失败","",resp);
        }

    }

    /**
     * 得到商品上架状态
     * @param data
     */
    private static void checkCommodity(Map<String, Object> data) {
        data.put("status",0);
        if(data.get("soldOut")==null){
            data.put("status", 1);
        }else {
            if(!String.valueOf(data.get("soldOut")).equals("0")){
                data.put("status", 1);
            }
        }

        if(data.get("delFlag")==null){
            data.put("status", 2);
        }else {
            if(!String.valueOf(data.get("delFlag")).equals("0")){
                data.put("status",2);
            }
        }
    }

    /** 批量更新商品数据 */
//    @RequestMapping("/updateCommodityId.jn")
    public void updateCommodityId(HttpServletRequest req, HttpServletResponse resp,
                          ModelMap model) throws Exception {

        Map<String, Object> param = new HashMap<String, Object>();

        List<String> listCommodityId = new ArrayList<String>();
        List<String> listCommodityImgId = new ArrayList<String>();
        List<String> listOrderdetailId = new ArrayList<String>();
        List<String> listCommodity3Id = new ArrayList<String>();

        List<String> listFestivalactId = new ArrayList<String>();
        List<String> listFestpicId = new ArrayList<String>();
        List<String> listActdetailId = new ArrayList<String>();

        //更新商品数据
        List<Map<String, Object>> list = czjcommodityService.getListBy(param);
        for (Map<String, Object> map : list) {
            listCommodityId.add(String.valueOf(map.get("id")));
        }
        List<Czjcommodity> listCommodity = czjcommodityService.queryByIds(listCommodityId);
        for (int i = 0; i < listCommodity.size(); i++) {
            listCommodity.get(i).setId(OrderType.COMMODITY.getIndex()+listCommodity.get(i).getId().substring(1));

        }
        czjcommodityService.deleteByIds(listCommodityId);
        czjcommodityService.saves(listCommodity);


        //更新商品图片数据
        List<Map<String, Object>> list2 = czjcommodityimageService.getListBy(param);
        for (Map<String, Object> map : list2) {
            listCommodityImgId.add(String.valueOf(map.get("id")));
        }
        List<Czjcommodityimage> listCommodityimage = czjcommodityimageService.queryByIds(listCommodityImgId);
        for (int i = 0; i < listCommodityimage.size(); i++) {
            if(listCommodityimage.get(i).getCommodityId()!=null&&listCommodityimage.get(i).getCommodityId().length()>1){
                listCommodityimage.get(i).setCommodityId(OrderType.COMMODITY.getIndex()+listCommodityimage.get(i).getCommodityId().substring(1));

            }

        }
        czjcommodityimageService.deleteByIds(listCommodityImgId);
        czjcommodityimageService.saves(listCommodityimage);

        //更新订单详情
        List<Map<String, Object>> list3 = czjorderdetailService.getListBy(param);
        for (Map<String, Object> map : list3) {
            listOrderdetailId.add(String.valueOf(map.get("id")));
        }
        List<Czjorderdetail> listOrderdetail = czjorderdetailService.queryByIds(listOrderdetailId);
        for (int i = 0; i < listOrderdetail.size(); i++) {
            if(listOrderdetail.get(i).getCommodityId()!=null&&listOrderdetail.get(i).getCommodityId().length()>1) {
                listOrderdetail.get(i).setCommodityId(OrderType.COMMODITY.getIndex() + listOrderdetail.get(i).getCommodityId().substring(1));

            }
        }
        czjorderdetailService.deleteByIds(listOrderdetailId);
        czjorderdetailService.saves(listOrderdetail);

        //更新严选商品
        List<Map<String, Object>> list4 = czjcommodity3Service.getList(param);
        for (Map<String, Object> map : list4) {
            listCommodity3Id.add(String.valueOf(map.get("id")));
        }
        List<Czjcommodity3> listCommodity3 = czjcommodity3Service.queryByIds(listCommodity3Id);
        for (int i = 0; i < listCommodity3.size(); i++) {
            if(listCommodity3.get(i).getCommodityId()!=null&&listCommodity3.get(i).getCommodityId().length()>1) {
                listCommodity3.get(i).setCommodityId(OrderType.COMMODITY.getIndex() + listCommodity3.get(i).getCommodityId().substring(1));

            }
        }
        czjcommodity3Service.deleteByIds(listCommodity3Id);
        czjcommodity3Service.saves(listCommodity3);

        //更新节日
        List<Czjfestivalact> czjfestivalactList = czjfestivalactService.getListBy(param);
        for (Czjfestivalact czjfestivalact : czjfestivalactList) {
            listFestivalactId.add(czjfestivalact.getFestivalActId());
        }
        for (int i = 0; i < czjfestivalactList.size(); i++) {
            czjfestivalactList.get(i).setFestivalActId(OrderType.ACTIVITY.getIndex()+czjfestivalactList.get(i).getFestivalActId().substring(1));
        }
//        for (Czjfestivalact s : czjfestivalactList) {
//            czjfestivalactService.updateFestivalAct(s);
//        }
        czjfestivalactService.deleteCzjfestivalactById(listFestivalactId);
        czjfestivalactService.saves(czjfestivalactList);

//        List<String> listFestpicId = new ArrayList<String>();
//        List<String> listActdetail = new ArrayList<String>();
        //更新节日图片
        List<Czjfestpic> listFestpic = czjfestpicService.getCzjfestpicList(param);
        for (int i = 0; i < listFestpic.size(); i++) {
            listFestpicId.add(listFestpic.get(i).getFestpicId());
            listFestpic.get(i).setFestivalActId(OrderType.ACTIVITY.getIndex()+czjfestivalactList.get(i).getFestivalActId().substring(1));

        }
        czjfestpicService.deleteByIds(listFestpicId);
        czjfestpicService.saves(listFestpic);

        //更新活动订单详情
        List<Czjactdetail> listActdetail = czjactdetailService.getListBy(param);
        for (int i = 0; i < listActdetail.size(); i++) {
            listActdetailId.add(listActdetail.get(i).getActDetaiId());
            listActdetail.get(i).setFestivalActId(OrderType.ACTIVITY.getIndex()+listActdetail.get(i).getFestivalActId().substring(1));

        }
        czjactdetailService.deleteByIds(listActdetailId);
        czjactdetailService.saves(listActdetail);

        //czj_top3
        List<Czjtop3> listTop3 = czjtop3Service.getListBy(param);
        for (int i = 0; i < listTop3.size(); i++) {
            listTop3.get(i).setRemark(OrderType.ACTIVITY.getIndex()+listTop3.get(i).getRemark().substring(1));
        }

        jsonResult(1,"","","",resp);



    }



    /**
     * 商品的待发货时取消订单(已支付情况),全额退款
     * @param orderCode
     * @param userinfoId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
    @RequestMapping("/canselOrder.jn")
    public void canselOrder(@RequestParam(required = true) String orderCode,
                       @RequestParam(required = true) Integer userinfoId,
                       HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model) throws Exception {
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderCode", orderCode);
            Czjorder czjorder = czjorderService.getOneBy(param);
            if(czjorder==null){
                jsonResult(0,"76","商品订单不存在！","",resp);
                return;
            }
            if(!userinfoId.equals(czjorder.getUserinfoId())){
                jsonResult(0,"97","用户权限不足","",resp);
                return;
            }
            if(OrderStatus.TOSENDGOODS.getIndex()==czjorder.getStatus()){
                czjorder.setStatus(OrderStatus.CANSEL.getIndex());
                Czjrefund czjrefund = czjrefundService.queryByOrderCode(orderCode);
                if(czjrefund==null){
                    czjrefund = new Czjrefund();
                }
                czjrefund.setUserinfoId(userinfoId);
                czjrefund.setOrderCode(orderCode);
                czjrefund.setRefundStatus(RefundStatus.RUNNING.getIndex());
                czjrefund.setRefundAmount(czjorder.getTotalAmount());
                czjrefund.setBusinessId(czjorder.getBusinessId());
                czjrefund.setCreatetime(new Date());


                czjrefund.setUserContent(LocalDateTime.getDate(czjrefund.getCreatetime(),"yyyy-MM-dd HH:mm:ss")+"\t用户发起退款......" );
                czjrefund.setDelFlag(0);
                if(StringUtils.isBlank(czjrefund.getRefundId())){
                    czjrefund.setRefundId(UUIDUtils.getUUID());
                    czjrefundService.insert(czjrefund);
                }else{
                    czjrefundService.update(czjrefund);
                }



                //退款完成保存订单
                czjorderService.update(czjorder);
                //退回优惠券 为未使用
                if(StringUtils.isNotBlank(czjorder.getCouponsId())){
                    //使用后更改优惠券状态为已使用
                    Czjawarduse czjawarduse32 = new Czjawarduse();
                    czjawarduse32.setAwarduseId(czjorder.getCouponsId());
                    Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
                    czjawarduse.setStatus(OrderStatus.UNUSE.getIndex());
                    czjawarduseService.updateCzjawarduse(czjawarduse);
                }

               jsonResult(1,"","正在为你取消订单","",resp);
            }else{
                jsonResult(0,"70","订单状态为待发货的时候才能取消订单","",resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    /**
     * 商品的待支付时取消订单(未支付情况)
     * @param orderCode
     * @param userinfoId
     * @param req
     * @param resp
     * @param model
     * @throws Exception
     */
   /* @RequestMapping("/cansel.jn")
    public void cansel(@RequestParam(required = true) String orderCode,
                            @RequestParam(required = true) Integer userinfoId,
                            HttpServletRequest req, HttpServletResponse resp,
                            ModelMap model) throws Exception {
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("orderCode", orderCode);
            Czjorder czjorder = czjorderService.getOneBy(param);
            if(czjorder==null){
                jsonResult(0,"76","商品订单不存在！","",resp);
                return;
            }
            if(!userinfoId.equals(czjorder.getUserinfoId())){
                jsonResult(0,"97","用户权限不足","",resp);
                return;
            }
            if(OrderStatus.RUNNING.getIndex()==czjorder.getStatus()){
                czjorderService.deleteById(czjorder.getId());
                if(StringUtils.isNotBlank(czjorder.getCouponsId())){
                    Czjawarduse czjawarduse = czjawarduseService.queryById(czjorder.getCouponsId());
                    if(OrderStatus.USE.getIndex()==czjawarduse.getStatus()){
                        czjawarduse.setStatus(OrderStatus.UNUSE.getIndex());
                        czjawarduseService.updateCzjawarduse(czjawarduse);
                    }*//*else if(OrderStatus.RECEIVED.getIndex()==czjawarduse.getStatus()){
                        czjawarduse.setStatus(OrderStatus.UNRECEIVED.getIndex());
                        czjawarduseService.updateCzjawarduse(czjawarduse);
                    }*//*
                }
                jsonResult(1,"","删除订单成功","",resp);
            }else{
                jsonResult(0,"70","订单状态为待支付的时候才能删除订单","",resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }*/


}
